#    Rubatom
#    Copyright (c) 2014 Sebastian Dufner
#
#    This file is part of Rubatom.
#
#    Rubatom is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Rubatom is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

require 'stringio'
require 'zlib'

require 'rubatom/structure/block'

##
#

module Rubatom
  class Structure
    class Chunks
      def self.deserialize(input)
        fail_on_unknown_format(input.read_many(:int))

        chunks = []
        (65540...input.size).step(5120) do |offset|
          f.seek offset

          byte, time = *input.read_many(:b, :i64)
          chunks << Chunk.deserialize(input)
        end

        new chunks
      end

      def initialize(chunks)
        @chunks = chunks
      end
    end

    class Chunk
      def self.deserialize(input)
        x, y, z, chunk_type, length =
            *input.read_many(:f32, :f32, :f32, :b, :i32)
        # Inflate chunk data
        inf = StringIO.new(Zlib::Inflate.inflate(input.read(length)))

        # Process block data
        blocks = Array.new(16) do
          Array.new(16) do
            Array.new(16) do
              block = Block.deserialize(inf)
              block unless block.id == 0
            end
          end
        end

        new(x, y, z, type, blocks)
      end

      def initialize(type, blocks)
        @type, @blocks = type, blocks
      end
      attr_accessor :x, :y, :z, :type

    end
  end
end
